#pragma once
#include "shared\dbg.h"

#include <vfw.h>
#include <atlimage.h>

namespace avlib{

class DbgGuiLeak
{
public:
    explicit DbgGuiLeak ()
    {
        _guiResCount = ::GetGuiResources (::GetCurrentProcess (),
                                          GR_GDIOBJECTS);
    }

	void report(){
		DWORD cnt = ::GetGuiResources (::GetCurrentProcess (),GR_GDIOBJECTS);
		log("Gui Resources count: %d\n" ,cnt);
	}
    ~DbgGuiLeak ()
    {
        int leaks = ::GetGuiResources (::GetCurrentProcess (), 
                                       GR_GDIOBJECTS) - _guiResCount;
        if (leaks != 0)
        {
            //std::cout << "Gui Resources Leaked: " << leaks << std::endl;
			log("Gui Resources Leaked: %d\n" ,leaks);
        }
    }
private:
    unsigned _guiResCount;
};


typedef void (*PROGRESS_CALLBACK)(void *data,int frame,int sample);
class AviFile{

private:
	DbgGuiLeak guileak;
	std::string m_filename;
	std::string m_thumb_file;


	PAVIFILE m_avi;
	HDC m_hdc;

	//vido
	int m_frames;

	AVISTREAMINFO mv_info;
	AVICOMPRESSOPTIONS	mv_compress_option;
	PAVISTREAM mv_stream;
	PAVISTREAM mv_compressed_stream;

	BITMAPINFO mBmpInfo;
	//unsigned mWidth;
	//unsigned mHeight;
	//unsigned mnBitsPerPixel;

	unsigned m_fps;


	//audio
	int m_samples;
	AVISTREAMINFO ma_info;
	PAVISTREAM ma_stream;
	WAVEFORMAT mWaveInfo;


	CRITICAL_SECTION cs;

	PROGRESS_CALLBACK m_progress_callback;
	LPVOID   m_callback_param;

	
public:

	AviFile(const char *fname);
	~AviFile();
	void close();
	//void set_

	void set_callback(PROGRESS_CALLBACK cb,LPVOID param){
		m_progress_callback = cb;
		m_callback_param = param;
	}

	void set_thumbnail(std::string fname){
		m_thumb_file = fname;
	}
	void set_fps(unsigned fps);
	void enum_encoding();
	bool InitVideo(int width,int height,int nBitsPerPixel);
	bool InitAudio(LPWAVEFORMAT af);

	bool AppendVideoFrame(LPVOID bits,int nBitsPerPixel = 0);
	bool AppendSoundSamples(LPVOID pBits,UINT nBytes);

	WAVEFORMAT & get_audio_format(){
		return mWaveInfo;
	}
	BITMAPINFO & get_video_format(){
		return mBmpInfo;
	}

	int get_frame_count(){
		return m_frames;
	}

	int get_sample_count(){
		return m_samples;
	}
	

};

};